package org.jeecg.modules.nurse_user_orders_nurses.controller;

import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.query.QueryGenerator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.nurse_user_orders.entity.NurseUserOrders;
import org.jeecg.modules.nurse_user_orders.service.INurseUserOrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;

import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.nurse_user_orders_nurses.entity.NurseUserOrdersNursesExecute;
import org.jeecg.modules.nurse_user_orders_nurses.entity.NurseUserOrdersNurses;
import org.jeecg.modules.nurse_user_orders_nurses.service.INurseUserOrdersNursesService;
import org.jeecg.modules.nurse_user_orders_nurses.service.INurseUserOrdersNursesExecuteService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.shiro.authz.annotation.RequiresPermissions;

/**
 * @Description: 订单分配
 * @Author: jeecg-boot
 * @Date: 2024-06-04
 * @Version: V1.0
 */
@Api(tags = "订单分配")
@RestController
@RequestMapping("/nurse_user_orders_nurses/nurseUserOrdersNurses")
@Slf4j
public class NurseUserOrdersNursesController extends JeecgController<NurseUserOrdersNurses, INurseUserOrdersNursesService> {

    @Autowired
    private INurseUserOrdersNursesService nurseUserOrdersNursesService;

    @Autowired
    private INurseUserOrdersNursesExecuteService nurseUserOrdersNursesExecuteService;

    @Autowired
    private INurseUserOrdersService nurseUserOrdersService;
    /*---------------------------------主表处理-begin-------------------------------------*/


    /**
     * 微信列表查询
     *
     * @param nursesId
     * @param req
     * @return
     */
    //@AutoLog(value = "订单分配-微信列表查询")
    @ApiOperation(value = "订单分配-微信列表查询", notes = "订单分配-微信列表查询")
    @GetMapping(value = "/listByWeChat")
    public Result<?> listByWeChat(
            @RequestParam(name = "nursesId") String nursesId,
            HttpServletRequest req) {
        List<Map<String, Object>> list = nurseUserOrdersNursesService.listByWeChat(nursesId);
        return Result.OK(list);
    }

    /**
     * 分页列表查询
     *
     * @param nurseUserOrdersNurses
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "订单分配-分页列表查询")
    @ApiOperation(value = "订单分配-分页列表查询", notes = "订单分配-分页列表查询")
    @GetMapping(value = "/list")
    @PermissionData(pageComponent = "nurse/nurse_user_orders_nurses/NurseUserOrdersNursesList")
    public Result<IPage<NurseUserOrdersNurses>> queryPageList(NurseUserOrdersNurses nurseUserOrdersNurses,
                                                              @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                              HttpServletRequest req) {
        QueryWrapper<NurseUserOrdersNurses> queryWrapper = QueryGenerator.initQueryWrapper(nurseUserOrdersNurses, req.getParameterMap());
        Page<NurseUserOrdersNurses> page = new Page<NurseUserOrdersNurses>(pageNo, pageSize);
        IPage<NurseUserOrdersNurses> pageList = nurseUserOrdersNursesService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param nurseUserOrdersNurses
     * @return
     */
    @AutoLog(value = "订单分配-添加")
    @ApiOperation(value = "订单分配-添加", notes = "订单分配-添加")
    @RequiresPermissions("nurse_user_orders_nurses:nurse_user_orders_nurses:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody NurseUserOrdersNurses nurseUserOrdersNurses) {

        NurseUserOrders nurseUserOrders = nurseUserOrdersService.getById(nurseUserOrdersNurses.getOrderId());
        if (nurseUserOrders == null) {
            return Result.error("未找到对应订单");
        }
        nurseUserOrders.setDispense("2");
        nurseUserOrdersService.updateById(nurseUserOrders);
        nurseUserOrdersNursesService.save(nurseUserOrdersNurses);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param nurseUserOrdersNurses
     * @return
     */
    @AutoLog(value = "订单分配-编辑")
    @ApiOperation(value = "订单分配-编辑", notes = "订单分配-编辑")
    @RequiresPermissions("nurse_user_orders_nurses:nurse_user_orders_nurses:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody NurseUserOrdersNurses nurseUserOrdersNurses) {
        nurseUserOrdersNursesService.updateById(nurseUserOrdersNurses);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单分配-通过id删除")
    @ApiOperation(value = "订单分配-通过id删除", notes = "订单分配-通过id删除")
    @RequiresPermissions("nurse_user_orders_nurses:nurse_user_orders_nurses:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        nurseUserOrdersNursesService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "订单分配-批量删除")
    @ApiOperation(value = "订单分配-批量删除", notes = "订单分配-批量删除")
    @RequiresPermissions("nurse_user_orders_nurses:nurse_user_orders_nurses:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.nurseUserOrdersNursesService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 导出
     *
     * @return
     */
    @RequiresPermissions("nurse_user_orders_nurses:nurse_user_orders_nurses:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, NurseUserOrdersNurses nurseUserOrdersNurses) {
        return super.exportXls(request, nurseUserOrdersNurses, NurseUserOrdersNurses.class, "订单分配");
    }

    /**
     * 导入
     *
     * @return
     */
    @RequiresPermissions("nurse_user_orders_nurses:nurse_user_orders_nurses:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, NurseUserOrdersNurses.class);
    }
    /*---------------------------------主表处理-end-------------------------------------*/


    /*--------------------------------子表处理-订单分配执行记录-begin----------------------------------------------*/

    /**
     * 通过主表ID查询
     *
     * @return
     */
    //@AutoLog(value = "订单分配执行记录-通过主表ID查询")
    @ApiOperation(value = "订单分配执行记录-通过主表ID查询", notes = "订单分配执行记录-通过主表ID查询")
    @GetMapping(value = "/listNurseUserOrdersNursesExecuteByMainId")
    public Result<IPage<NurseUserOrdersNursesExecute>> listNurseUserOrdersNursesExecuteByMainId(NurseUserOrdersNursesExecute nurseUserOrdersNursesExecute,
                                                                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                                                HttpServletRequest req) {
        QueryWrapper<NurseUserOrdersNursesExecute> queryWrapper = QueryGenerator.initQueryWrapper(nurseUserOrdersNursesExecute, req.getParameterMap());
        Page<NurseUserOrdersNursesExecute> page = new Page<NurseUserOrdersNursesExecute>(pageNo, pageSize);
        IPage<NurseUserOrdersNursesExecute> pageList = nurseUserOrdersNursesExecuteService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param nurseUserOrdersNursesExecute
     * @return
     */
    @AutoLog(value = "订单分配执行记录-添加")
    @ApiOperation(value = "订单分配执行记录-添加", notes = "订单分配执行记录-添加")
    @PostMapping(value = "/addNurseUserOrdersNursesExecute")
    public Result<String> addNurseUserOrdersNursesExecute(@RequestBody NurseUserOrdersNursesExecute nurseUserOrdersNursesExecute) {
        nurseUserOrdersNursesExecuteService.save(nurseUserOrdersNursesExecute);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param nurseUserOrdersNursesExecute
     * @return
     */
    @AutoLog(value = "订单分配执行记录-编辑")
    @ApiOperation(value = "订单分配执行记录-编辑", notes = "订单分配执行记录-编辑")
    @RequestMapping(value = "/editNurseUserOrdersNursesExecute", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> editNurseUserOrdersNursesExecute(@RequestBody NurseUserOrdersNursesExecute nurseUserOrdersNursesExecute) {
        nurseUserOrdersNursesExecuteService.updateById(nurseUserOrdersNursesExecute);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单分配执行记录-通过id删除")
    @ApiOperation(value = "订单分配执行记录-通过id删除", notes = "订单分配执行记录-通过id删除")
    @DeleteMapping(value = "/deleteNurseUserOrdersNursesExecute")
    public Result<String> deleteNurseUserOrdersNursesExecute(@RequestParam(name = "id", required = true) String id) {
        nurseUserOrdersNursesExecuteService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "订单分配执行记录-批量删除")
    @ApiOperation(value = "订单分配执行记录-批量删除", notes = "订单分配执行记录-批量删除")
    @DeleteMapping(value = "/deleteBatchNurseUserOrdersNursesExecute")
    public Result<String> deleteBatchNurseUserOrdersNursesExecute(@RequestParam(name = "ids", required = true) String ids) {
        this.nurseUserOrdersNursesExecuteService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 导出
     *
     * @return
     */
    @RequestMapping(value = "/exportNurseUserOrdersNursesExecute")
    public ModelAndView exportNurseUserOrdersNursesExecute(HttpServletRequest request, NurseUserOrdersNursesExecute nurseUserOrdersNursesExecute) {
        // Step.1 组装查询条件
        QueryWrapper<NurseUserOrdersNursesExecute> queryWrapper = QueryGenerator.initQueryWrapper(nurseUserOrdersNursesExecute, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // Step.2 获取导出数据
        List<NurseUserOrdersNursesExecute> pageList = nurseUserOrdersNursesExecuteService.list(queryWrapper);
        List<NurseUserOrdersNursesExecute> exportList = null;

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        } else {
            exportList = pageList;
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //此处设置的filename无效,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.FILE_NAME, "订单分配执行记录");
        mv.addObject(NormalExcelConstants.CLASS, NurseUserOrdersNursesExecute.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("订单分配执行记录报表", "导出人:" + sysUser.getRealname(), "订单分配执行记录"));
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 导入
     *
     * @return
     */
    @RequestMapping(value = "/importNurseUserOrdersNursesExecute/{mainId}")
    public Result<?> importNurseUserOrdersNursesExecute(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<NurseUserOrdersNursesExecute> list = ExcelImportUtil.importExcel(file.getInputStream(), NurseUserOrdersNursesExecute.class, params);
                for (NurseUserOrdersNursesExecute temp : list) {
                    temp.setOrdersNursesId(mainId);
                }
                long start = System.currentTimeMillis();
                nurseUserOrdersNursesExecuteService.saveBatch(list);
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                return Result.OK("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-订单分配执行记录-end----------------------------------------------*/


}
